<template>
  <view class="container">
    <NavBar
      :title="!flag ? '心得详情' : '上传学习心得'"
      @clickRightFn="clickRightFn"
      :iconClass="!flag ? '' : 'icon-lishijilu'"
    />
    <view class="container-item">
      <uni-forms-item label="标题" class="uni-forms-item" required>
        <input v-if="flag" v-model="baseFormData.title" placeholder="请输入" />
        <text>{{ pageInfo.title }}</text>
      </uni-forms-item>

      <uni-forms
        ref="baseForm"
        :modelValue="baseFormData"
        labelWidth="100px"
        label-position="left"
        style=""
      >
        <uni-forms-item label="文件" required v-if="flag">
          <lsj-upload
            class="uni-forms-item"
            ref="lsjUpload"
            childId="upload1"
            :size="uploadconfig2.size"
            :instantly="uploadconfig2.instantly"
            :formats="fileAccept"
            :option="option"
            @change="onChange"
            @uploadEnd="onuploadEnd"
            @progress="onProgress"
            @fail="failFile"
          >
            <view
              style="width: 100%; text-align: right; color: #3c95ff"
              @click="fuckyou"
            >
              添加
            </view>
          </lsj-upload>
        </uni-forms-item>
        <progress v-if="percent !=0&&percent !=100" :percent="percent" show-info stroke-width="3" />
        <view v-if="flag && baseFormData.fileUrl.length">
          <view
            class="file_list"
            v-for="(item, index) in baseFormData.fileUrl"
            :key="index"
          >
            <view
              class="file_list_item"
              @click="prevFileClick(item)"
            >
              <view>{{ item.accessoryName }}</view>
            </view>
            <view
              class="iconfont icon-close"
              @click="delFile(index)"
            ></view>
          </view>
        </view>

        <uni-forms-item
          label="文件"
          v-if="!flag"
          style="border-bottom: none"
        ></uni-forms-item>
        <view v-if="!flag" style="margin-bottom: 20rpx">
          <view class="file_list" v-for="(item, index) in fileUrl" :key="index">
            <view
              class="file_list_item"
              @click="prevFileClick(item)"
            >
              <view>{{ item.accessoryName }}</view>
            </view>
          </view>
        </view>

        <uni-forms-item label="学习类型" class="uni-forms-item" required>
          <text>学习心得</text>
        </uni-forms-item>

        <!-- 				<uni-forms-item label="课件类型" required>
					<uni-data-select v-model="baseFormData.learningType" :localdata="range2" placeholder="请选择"
						@change="changeLearningType">
					</uni-data-select>
				</uni-forms-item> -->

        <uni-forms-item label="上传人" required>
          <text v-if="flag">{{ baseFormData.userName }}</text>
          <text v-else>{{ pageInfo.userName }}</text>
        </uni-forms-item>

        <uni-forms-item label="上传时间" required>
          <text v-if="flag">{{ baseFormData.createTime }}</text>
          <text v-else>{{ pageInfo.createTime }}</text>
        </uni-forms-item>

        <view style="padding-top: 20px"></view>
        <view class="btns" v-if="flag">
          <button class="save-draft" @click="resetUpload">取消</button>
          <button
            class="publish"
            :disabled="disabledPublish"
            :loading="publishLoading"
            @click="saveDraft"
          >
            确定
          </button>
        </view>
        <view class="btns" v-if="!flag">
          <button
            class="publish"
            style="background: #e86565; width: 700rpx"
            :disabled="disabledPublish"
            :loading="publishLoading"
            @click="delInfo"
          >
            删除
          </button>
        </view>
        <view style="padding-top: 20px"></view>
      </uni-forms>
    </view>
  </view>
</template>

<script>
// 接口
import {
  apiEducationList, // 学习类型
  apiUploadData, // 上传
  apiDeleteUploadXue, // 5 上传批量删除
  apiDeleteDownList, // 11
} from "@/net/educationalLearning.js";

import { previewPic, format, getDateFn } from "@/utils/fun.js";
import {
  prevFile, // 预览文件
} from "@/utils/preview.js";
import { uploadconfig2 } from "@/const";

import NavBar from "@/components/NavBar.vue";
export default {
  components: {
    NavBar,
  },
  data() {
    return {
      uploadconfig2,
      option: {
        url: uploadconfig2.url,
        name: "file",
        header: {
          Authorization: uni.getStorageSync("token"), platform: 'APP'
        },
        formData: {},
      },

      // ------------------
      percent:0,
      pageInfo: {},
      flag: true,
      fileAccept: "", //上传文件格式限制
      imgWidth: 200,
      imgHeight: 132,
      range2: [], //学习类型

      // 开始时间和结束时间限制

      uploadURL: "/masses/common/upload", // 上传接口地址
      disabledPublish: false,
      publishLoading: false,
      // 文件回显列表
      files: new Map(),

      suffix: "", //后缀名
      baseFormData: {
        learningType: "",
        fileUrl: [],
      },
    };
  },
  computed: {},
  watch: {},
  onLoad(options) {
    console.log(JSON.stringify(options));
    if (JSON.stringify(options) != "{}") {
      this.flag = options.flag == "false" ? false : true;
      this.pageInfo = JSON.parse(uni.getStorageSync("itemParams"));
      this.fileUrl = JSON.parse(this.pageInfo.fileUrl);
      this.pageInfo.createTime = getDateFn();
    }

    this.baseFormData = {
      learningType: "",
      fileUrl: [],
    };

    // this.getApiChamberList();
    setTimeout(() => {
      this.fuckyou();
    }, 1000);

    if (this.flag) {
      this.init();
    }
  },
  methods: {
    // 删除
    delInfo() {
      console.log(this.pageInfo);
      // 删除该条数据
      if (this.pageInfo.djStudyId) {
        apiDeleteUploadXue(this.pageInfo.djStudyId)
          .then((res) => {
            if (res.code === 0) {
              uni.showToast({
                title: "删除成功",
                icon: "success",
                mask: true,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 2000);
            } else {
              uni.showToast({
                title: "删除失败",
                icon: "error",
                mask: true,
              });
            }
          })
          .catch((err) => {
            uni.showToast({
              title: "删除失败",
              icon: "error",
              mask: true,
            });
          });
      } else if (this.pageInfo.recordId) {
        // 删除下载的记录
        apiDeleteDownList(this.pageInfo.recordId)
          .then((res) => {
            if (res.code === 0) {
              uni.showToast({
                title: "删除成功",
                icon: "success",
                mask: true,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 2000);
            } else {
              uni.showToast({
                title: "删除失败",
                icon: "error",
                mask: true,
              });
            }
          })
          .catch(() => {
            uni.showToast({
              title: "删除失败",
              icon: "error",
              mask: true,
            });
          });
      }
    },

    init() {
      console.log(JSON.parse(uni.getStorageSync("loginUserInfo")));
      this.baseFormData.userName = JSON.parse(
        uni.getStorageSync("loginUserInfo")
      ).userName;
      this.baseFormData.userId = JSON.parse(
        uni.getStorageSync("loginUserInfo")
      ).uid;
      this.baseFormData.createTime = getDateFn();

      this.getEducationList();
    },

    // 取消上传
    resetUpload() {
      this.baseFormData = {
        learningType: "",
        fileUrl: [],
      };
      this.init();
    },

    // 预览上传的文件
    prevFileClick(item) {
      prevFile(item);
    },

    uniShowToast(title, icon = "error") {
      uni.showToast({
        title,
        icon,
      });
    },

    // 预览 图片
    prePic(url) {
      let arr = [url];
      previewPic(arr);
    },

    // 删除附件
    delFile(i) {
      this.baseFormData.fileUrl.splice(i, 1);
      this.fuckyou();
    },

    getEducationList() {
      apiEducationList()
        .then((res) => {
          console.log(res);
          if (res.code === 0) {
            this.range2 = res.data.map((v) => {
              return {
                value: v.key,
                text: v.value,
              };
            });

            this.range2.length = 4;
          } else {
            this.range2 = [];
          }
        })
        .catch((err) => {
          console.log(err);
          this.range2 = [];
        });
    },

    // 穿刺一击让他们的遮罩层消失
    chuanci() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
    },
    // 穿刺一击让他们的遮罩层消失
    chuanci2() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
      this.$forceUpdate();
    },
    fuckyou() {
      console.log(this.$refs.lsjUpload);
      this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
      this.$forceUpdate();
    },

    // 文件上传时触发
    picProgress(file) {
      console.log(file);
    },
    // 上传成功触发
    successPic(file) {
      console.log(file);
    },
    // 上传失败触发
    failPic(file) {
      console.log(file);
    },
    // 文件从列表移除时触发
    deletePic(file) {
      console.log(file);
    },

    // 上传文件的操作
    // 选择文件触发，返回所有已选择文件Map集合
    onChange(files) {
      this.files = files;
      this.$forceUpdate();
    },
    failFile() {
      uni.showToast({
	      title: '上传失败',
        icon: 'error',
        mask: true,
	      duration: 1500
      });
    },
    onProgress(res){
      this.percent = res.progress;
		},
    // 上传结束回调，返回参数与progress一致
    onuploadEnd(item) {
      let res = JSON.parse(item.responseText);

      if (res.code === 0) {
        this.baseFormData.fileUrl.push({
          accessoryUrl: res.data.url,
          accessoryName: res.data.fileName,
        });
        this.suffix = item.name.substring(item.name.lastIndexOf(".") + 1);
      }

      // 更新当前窗口状态变化的文件
      this.files.set(item.accessoryName, item);

      // 强制更新视图
      this.$forceUpdate();
    },

    // 保存草稿
    saveDraft() {
      // this.baseFormData.learningType
			if(!this.baseFormData.title){
				uni.showToast({
				  title: "请填写标题",
				  icon: "error",
				  mask: true,
				  duration: 1000,
				});
				return;
			}
      if (!this.baseFormData.fileUrl.length) {
        uni.showToast({
          title: "请选择文件",
          icon: "error",
          mask: true,
          duration: 1000,
        });
        return;
      }

      let data = {
        learningType: 5,
        userId: this.baseFormData.userId,
        userName: this.baseFormData.userName,
        title: this.baseFormData.title,
        status: 1,
      };
			
      // 文件
      let urlArr = [];
      if (this.baseFormData.fileUrl && this.baseFormData.fileUrl.length > 0) {
        // let fileUrlArr = this.baseFormData.fileUrl.map((v) => {
        //   return {
        //     accessoryName: v.name,
        //     accessoryUrl: v.url,
        //   };
        // });
        let fileUrlArr2 = this.baseFormData.fileUrl.map((v) => {
          return v.accessoryUrl;
        });

        data.fileUrl = JSON.stringify(this.baseFormData.fileUrl);
        urlArr = urlArr.concat(fileUrlArr2);
      }

      data.accessoryUrl = JSON.stringify(urlArr);
      apiUploadData(data)
        .then((res) => {
          console.log(res);
          if (res.code === 0) {
            uni.showToast({
              title: "操作成功",
              icon: "success",
              mask: true,
              duration: 1000,
            });
          } else {
            uni.showToast({
              title: "操作失败",
              icon: "error",
              mask: true,
              duration: 1000,
            });
          }
          this.resetUpload();
        })
        .catch((err) => {
          console.log(err);
          uni.showToast({
            title: "操作失败",
            icon: "error",
            mask: true,
            duration: 1000,
          });
          this.resetUpload();
        });
    },

    clickRightFn() {
      let data = {
        index: 2,
        title: "学习心得",
      };
      uni.navigateTo({
        url: `../../DJActivityDaylist/index?data=${JSON.stringify(data)}`,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "/static/dangjian.scss";
page {
  background: #fff;
  color: #999999;
  height: 100%;
  overflow: hidden;
}

.uni-forms-item {
  border-bottom: 1px solid #f2f2f2;
  display: flex;
  align-items: center;
  text-align: right;
}

/* 学习类型箭头 */
::v-deep .uni-popper__arrow {
  left: 80% !important;
  /* right: 10% !important; */
}
.container{
  background: #fff;
  height: 100%;
}

.container-item {
  width: 700rpx;
  margin: 0 auto;
}

.btns {
  width: 700rpx;
  display: flex;
  align-items: center;
  justify-content: space-around;
  position: absolute;
  bottom: 40rpx;
}

.btns button {
  width: 300rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 10rpx;
  text-align: center;
  color: #fff;
  font-size: 26rpx;
}

.save-draft {
  background: #d3d3d3;
}

.publish {
  background: #3c95ff;
}

// .file_list {
//   box-sizing: border-box;
//   padding: 0 30rpx;
//   display: flex;
//   align-items: center;
//   justify-content: space-between;
//   width: 700rpx;
//   min-height: 100rpx;
//   background: #f3f5f8;
//   border-radius: 8rpx;
//   border: 1px solid #d6dbe3;
//   margin-bottom: 10rpx;
// }

/* 预览图片 */
.cover_pic {
  width: 200rpx;
  height: 132rpx;
  position: absolute;
  right: 0;
}

.cover_pic i {
  color: red;
  font-size: 36rpx;
  position: absolute;
  z-index: 100;
  right: 0;
  top: 0;
}

/* 参与人员 */
.join_peo {
  position: absolute;
  right: 0;
  width: 150rpx;
  height: 70rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10rpx;
  box-sizing: border-box;
  font-size: 24rpx;
  color: #6a6a6a;
}

.picker_views {
  position: absolute;
  z-index: 100;
  top: 100rpx;
  width: 100%;
  height: 350rpx;
  background: #fff;
  border-radius: 8rpx;
  border: 2rpx solid #e5e5e5;
  text-align: center;
}

.upload_img {
  padding-top: 20rpx;
  box-sizing: border-box;
  width: 200rpx;
  height: 140rpx;
  background-color: rgba(214, 219, 227, 0.6);
  color: #3b95ff;
  text-align: center;
}

.upload_img i {
  display: inline-block;
}

/* 活动内容 */
.textarea_con {
  margin-bottom: 20rpx;
  width: 700rpx;
  position: relative;
}

.textarea_text {
  margin: 0 auto;
  width: 700rpx;
  min-height: 220rpx;
  background: #f3f5f8 !important;
  border-radius: 8rpx;
  border: 1rpx solid #d6dbe3;
  padding: 20rpx;
  box-sizing: border-box;
}

.textarea_plac {
  font-size: 30rpx;
  font-weight: 500;
  color: #0e1634;
}

/* 上传封面 1 */
.upload_btn {
  background: #f3f5f8;
  border-radius: 8rpx;
  /* border: 1px solid #D6DBE3; */
  float: right;
  text-align: center;
  position: relative;
  overflow: hidden;
}

.upload_btn .upload_text {
  width: 100%;
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 10;
  transform: translate(-50%, -50%);
}

.upload_btn .upload_text view {
  width: 110% !important;
}

/* 上传封面 2 */

/* 重置样式 */
::v-deep .is-input-border,
::v-deep .uni-select,
::v-deep .uni-date-x--border {
  text-align: right;
  border: none !important;
}

::v-deep .uni-date {
  position: absolute;
  right: 0;
  /* 		width: 400rpx; */
}

::v-deep .icon-xiangxia1:before {
  content: "&#xe603;" !important;
}

::v-deep .uniui-calendar {
  position: absolute;
  right: 0;
}

::v-deep .uni-date-editor--x {
  text-align: right !important;
  padding-right: 5rpx;
}

/* 封面上传控件 */
::v-deep .file-picker__box {
  position: absolute !important;
  right: 0 !important;
  width: 200rpx !important;
  height: 132rpx !important;
}

::v-deep .file-picker__box-content {
  border: none !important;
}

::v-deep .uni-input-placeholder,
::v-deep .uni-select__input-text,
::v-deep .uni-select__input-placeholder,
.join_peo text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  color: #0e1634 !important;
}

/* 链接 */
.url_class {
  background: red;
  text-align: left;
  width: 702rpx;
  background: #f3f5f8;
  border-radius: 8rpx;
  border: 1px solid #d6dbe3;
  border: 1px solid #ccc;
}
::v-deep .uni-forms-item__label {
  font-size: 32rpx !important;
  color: #000 !important;
}
/* uni-forms-item__content 参与人员 */
::v-deep .uni-forms-item__content,
::v-deep .uni-select__input-text,
::v-deep .uni-textarea-textarea,
::v-deep .uni-input-input,
::v-deep .uni-input-placeholder {
  color: #999 !important;
  font-size: 28rpx !important;
}
::v-deep .uni-forms-item {
  border: none !important;
}
</style>
